<?php

require_once( "common.inc" );

class NMNet
{
	private $_data;
	private $_activation;
	private $_deactivation;
	
	function __construct( $data )
	{
		global $NMZoneUtc, $NMZoneLocal;
		
		$this->_data = $data;
		if ( !is_null( $data[ "activation_time" ] ) )
			$this->_activation = new DateTime( $data[ "activation_time" ], $NMZoneUtc );
		if ( !is_null( $data[ "deactivation_time" ] ) )
			$this->_deactivation = new DateTime( $data[ "deactivation_time" ], $NMZoneUtc );
	}
	
	function IsActive()
	{
		return ( bool ) $this->_data[ "is_active" ];
	}
	
	function GetActivationSpan()
	{
		if ( isset( $this->_activation ) )
		{
			$startTime = $this->_activation->format( "U" );
			if ( isset( $this->_deactivation ) )
			{
				$endTime = $this->_deactivation->format( "U" );
			}
			else
			{
				$endTime = time();
			}
			$span = $endTime - $startTime;
			$hours = ( int ) ( $span / 3600 );
			$minutes = ( int ) ( ( $span - $hours * 3600 ) / 60 ) + 1;
			$hoursLabel = ( $hours == 1 ? "hour" : "hours" );
			$minutesLabel = ( $minutes == 1 ? "minute" : "minutes" );
			return "$hours $hoursLabel $minutes $minutesLabel";
		}
		else
		{
			return NULL;
		}
	}
	
	function GetActivationTime()
	{
		global $NMZoneLocal;
		
		if ( isset( $this->_activation ) )
		{
			$local = $this->_activation;
			$local->setTimezone( $NMZoneLocal );
			return $local->format( "r" );
		}
		else
		{
			return NULL;
		}
	}
	
	function Write()
	{
		$link = new NMHtmlItem( "a", $this->_data[ "name" ] . " on {$this->_data[ "frequency" ]}" );
		$link->AddAttribute( "href", "details.php?net_id=" . $this->_data[ "net_id" ] );
		$content = $link->Format() . "<br/>";
		$activationTime = $this->GetActivationTime();
		if ( isset( $activationTime ) )
		{
			$span = $this->GetActivationSpan();
			$content .= "Activated $activationTime by {$this->_data[ 'logger_id' ]} for $span";
		}
		else
		{
			$content .= "Not formally activated";
		}
		$listItem = new NMHtmlItem( "li", $content );
		$listItem->Write();
	}
}

function NMListNets( $list )
{
	foreach ( $list as $value )
	{
		$value->Write();
	}
}

if ( NMOpenDB() )
{
	if ( $data = mysql_query( "SELECT * FROM nets ORDER BY net_id DESC" ) )
	{
		while ( $row = mysql_fetch_assoc( $data ) )
		{
			$net = new NMNet( $row );
			if ( $net->IsActive() )
				$activeNets[] = $net;
			else
				$oldNets[] = $net;
		}
	}
}

?>
